<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>可拖动元素</title>
	</head>
	<style>
		div{
			position: absolute;
			width: 100px;
			height: 100px;
			background-color: aqua;
		}
	</style>
	<body>
		<div id="draggable-element">可拖动的元素</div>
		
		<script>
			
			// 获取可拖动的元素
			const draggableElement = document.getElementById('draggable-element');
			
			// 用于记录鼠标按下时的初始位置
			let startMouseX = 0;
			let startMouseY = 0;
			
			// 用于记录元素初始位置
			let startElementX = 0;
			let startElementY = 0;
			
			// 当鼠标按下时触发的事件处理函数
			const handleMouseDown = (event) => {
			  // 记录鼠标按下时的初始位置和元素初始位置
			  startMouseX = event.clientX;
			  startMouseY = event.clientY;
			  startElementX = draggableElement.offsetLeft;
			  startElementY = draggableElement.offsetTop;
			
			  // 添加鼠标移动和鼠标释放事件的监听器
			  document.addEventListener('mousemove', handleMouseMove);
			  document.addEventListener('mouseup', handleMouseUp);
			};
			
			// 当鼠标移动时触发的事件处理函数
			const handleMouseMove = (event) => {
			  // 计算鼠标移动的距离
			  const moveX = event.clientX - startMouseX;
			  const moveY = event.clientY - startMouseY;
			
			  // 计算元素的新位置
			  const newElementX = startElementX + moveX;
			  const newElementY = startElementY + moveY;
			
			  // 更新元素的位置
			  draggableElement.style.left = newElementX + 'px';
			  draggableElement.style.top = newElementY + 'px';
			};
			
			// 当鼠标释放时触发的事件处理函数
			const handleMouseUp = () => {
			  // 移除鼠标移动和鼠标释放事件的监听器
			  document.removeEventListener('mousemove', handleMouseMove);
			  document.removeEventListener('mouseup', handleMouseUp);
			};
			
			// 为元素添加鼠标按下事件的监听器
			draggableElement.addEventListener('mousedown', handleMouseDown);
			
		</script>
	</body>
</html>